package com.z.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.z.dao.*;
import com.z.entity.*;
import com.z.service.RegisterService;
import com.z.utils.SaltUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service(value = "registerService")
@Transactional
public class RegisterServiceImpl implements RegisterService {

    @Resource
    private UserDao userDao;
    @Resource
    private UserRoleDao userRoleDao;
    @Resource
    private RoleDao roleDao;
    @Resource
    private PermsRoleDao permsRoleDao;
    @Resource
    private PermsDao permsDao;

    @Override
    public int register(User user) {
        User user1 = new User();
        user1.setUsername(user.getUsername());
        String salt = SaltUtils.getSalt(6);
        user1.setSalt(salt);
        Md5Hash md5Hash = new Md5Hash(user.getPassword(), salt, 1024);
        String password = md5Hash.toHex();
        user1.setPassword(password);
        return userDao.insert(user1);
    }

    @Override
    public User login(String username) {
        return userDao.selectOne(new QueryWrapper<User>().eq("username", username));
    }

    @Override
    public List<Role> selectAllRoles(String username) {
        User user = new User();
        user.setUsername(username);
        User one = userDao.selectOne(new QueryWrapper<User>().eq("username", user.getUsername()));
        List<UserRole> userRoles = userRoleDao.selectList(new QueryWrapper<UserRole>().eq("userid", one.getId()));
        List<Role> collect = userRoles.stream().map((userRole) -> {
            Role role = roleDao.selectById(userRole.getRoleid());
            return role;
        }).collect(Collectors.toList());
        return collect;
    }

    @Override
    public List<Perms> findPermsByRoleId(Long id) {
        List<PermsRole> permsRoles = permsRoleDao.selectList(new QueryWrapper<PermsRole>().eq("roleid", id));
        List<Perms> collect = permsRoles.stream().map((permsRole) -> {
            Perms perms = permsDao.selectById(permsRole.getRoleid());
            return perms;
        }).collect(Collectors.toList());
        return collect;
    }


}
